<template>
  <section class="firm-manage" v-cloak>
    <div class="info-title"><span class="icon"></span>批量配置</div>
    <form @keyup.enter="search" @submit.prevent>
      <el-row class="search-box">
        <el-col :span="24">
          <label for="" class="choose">
            <span>操作人：</span>
            <el-select v-model="form.user_id" size="small" class="width200" placeholder="请选择操作人">
              <el-option
                v-for="item in listscustomer"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </label>
          <label for="" class="choose">
            <span>操作时间：</span>
            <el-date-picker v-model="form.Timepicker[0]" type="date" size="small"  class="width150" placeholder="请选择时间" :picker-options='dateTstart'></el-date-picker>
            &nbsp;至&nbsp;
            <el-date-picker v-model="form.Timepicker[1]" type="date" size="small"  class="width150" placeholder="请选择时间" :picker-options='dateTend'></el-date-picker>
          </label>
          <label for="" class="choose">
            <el-button icon="search" type="primary" size="small" @click="search" v-resetClick>搜索</el-button>
          </label>
        </el-col>
      </el-row>
    </form>
    <el-row class="title">
      <el-button class="titleright" type="primary" size="small" @click="addFirm" v-resetClick>新增</el-button>
    </el-row>
    <el-row class="data-list">
      <el-table :data="lists" border class="table_box" style="width:100%" :empty-text="emptyText">
        <el-table-column prop="created" label="操作时间" align="center"></el-table-column>
        <el-table-column prop="name" label="操作人" align="center"></el-table-column>
        <el-table-column prop="content" label="批量设置参数" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.content.type">
              <span v-if="scope.row.content.type === 1">设备模式:先测温后扫码</span>
              <span v-if="scope.row.content.type === 2">设备模式:先扫码后测温</span>
              <span v-if="scope.row.content.type === 3">设备模式:只扫码</span>
            </div>
            <div v-if="scope.row.content.temperature">温度:{{scope.row.content.temperature}}度</div>
            <div v-if="scope.row.content.switch">开关:{{scope.row.content.switch ? '开启' : '关闭'}}</div>
            <div v-if="scope.row.content.volume">音量:{{scope.row.content.volume}}%</div>
            <div v-if="scope.row.content.notice">语音播报:{{scope.row.content.notice}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
              <el-button type="text" @click="editFirm(scope.row)">设备列表</el-button>
          </template>
        </el-table-column>
      </el-table>
      <paginate :callback="pageObj.callback" :page="pageObj.page"></paginate>
    </el-row>
    <el-dialog :title="ruleForm.id ? '编辑批量设置' : '新增批量设置'" :visible.sync="isDialogShow" :show-close="false" :destroy-on-close="true" :close-on-click-modal="false" width="40%" custom-class="customWidth">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm">
        <el-form-item label="升级包类型:" :label-width="formLabelWidth" prop="type">
          <el-radio-group v-model="ruleForm.type">
            <el-radio :label="1">手动勾选</el-radio>
            <el-radio :label="2">文件上传</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设备列表:" :label-width="formLabelWidth" prop="device_list" v-if="ruleForm.type === 1">
          <el-button type="primary" @click="queryEquipmentFun" size="small">选择设备</el-button>（当前已选择<span style="color: #FF0000;font-size: 18px;padding: 0 5px;">{{ruleForm.device_list.length}}</span>台设备）
        </el-form-item>
        <el-form-item label="设备列表:" :label-width="formLabelWidth" v-if="ruleForm.type === 2" prop="file">
          <div style="display: flex;align-items: center;">
            <el-upload :on-change="handlePreview" :auto-upload="false" :show-file-list="false">
              <el-button size="small" type="primary">文件上传</el-button>
            </el-upload>（当前已上传<span style="color: #FF0000;font-size: 18px;padding: 0 5px;">{{ruleForm.file.length}}</span>台设备）
          </div>
        </el-form-item>
        <!-- <div style="display: flex;flex-direction: column; padding-left: 30px;padding-bottom: 30px;" v-if="ruleForm.type === 2 && ruleForm.file && ruleForm.file.length">
          <div v-for="(item, index) in ruleForm.file" :key="index">
            <span style="padding-right: 20px;line-height: 30px;font-size: 14px;font-weight: 600;">{{item}}</span><i class="el-icon-close" @click="delfile(index)"></i>
          </div>
        </div> -->
        <el-form-item label="批量设置参数:" :label-width="formLabelWidth" prop="content">
          <div>
            <el-checkbox v-model="ruleForm.content[0].istrue">设备模式</el-checkbox>
            <el-select v-model="ruleForm.content[0].type" size="small" class="width200">
              <el-option label="先测温后扫码" :value="1"></el-option>
              <el-option label="先扫码后测温" :value="2"></el-option>
              <el-option label="只扫码" :value="3"></el-option>
            </el-select>
          </div>
          <div><el-checkbox v-model="ruleForm.content[1].istrue">温度</el-checkbox><el-input size="small" v-model="ruleForm.content[1].temperature" autocomplete="off" style="width: 100px;margin-left: 32px;" placeholder=""></el-input><span>  度</span></div>
          <div>
            <el-checkbox v-model="ruleForm.content[2].istrue" style="margin-right: 4px;">开关<span style="color: #FF0000;">（温度）</span></el-checkbox>
            <el-switch v-model="ruleForm.content[2].switch"></el-switch>
          </div>
          <div><el-checkbox v-model="ruleForm.content[3].istrue">音量</el-checkbox><el-input size="small" v-model="ruleForm.content[3].volume" autocomplete="off" style="width: 100px;margin-left: 32px;" placeholder="" oninput="if(!/^[1-9]+$/.test(value)) value=value.replace(/\D/g,'');if(value>12)value=12;if(value<1)value=null"></el-input><span>（请输入1~12）</span></div>
          <div><el-checkbox v-model="ruleForm.content[4].istrue">语音播报</el-checkbox><el-input size="small" v-model="ruleForm.content[4].notice" autocomplete="off" style="width: 250px;margin-left: 4px;" placeholder=""></el-input></div>

        </el-form-item>
        <el-form-item label="备  注:" :label-width="formLabelWidth" prop="remarks">
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入备注信息" v-model="ruleForm.remarks" autocomplete="off" style="width: 350px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm('ruleForm', 2)">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm', 1)">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="二次确认" :visible.sync="isDialogVisible" :destroy-on-close="true" :close-on-click-modal="false" width="30%" custom-class="customWidth">
      <div style="padding-left: 30px;">
        <div class="textNameTX1" v-if="ruleForm.type === 1">批量设置共 <span style="color: #ff0000;">{{ruleForm.device_list.length}}</span> 台设备</div>
        <div class="textNameTX1" v-if="ruleForm.type === 2">批量设置共 <span style="color: #ff0000;">{{ruleForm.file.length}}</span> 台设备</div>
        <div class="textNameTX1">批量设置参数：</div>
        <div class="textNameTX1 padding-l60" v-if="ruleForm.content[0].istrue">
          <span>设备模式:</span>
          <span v-if="ruleForm.content[0].type === 1">先测温后扫码</span>
          <span v-if="ruleForm.content[0].type === 2">先扫码后测温</span>
          <span v-if="ruleForm.content[0].type === 3">只扫码</span>
        </div>
        <div class="textNameTX1 padding-l60" v-if="ruleForm.content[1].istrue">
          <span>温度:</span>
          <span>{{ruleForm.content[1].temperature}} 度</span>
        </div>
        <div class="textNameTX1 padding-l60" v-if="ruleForm.content[2].istrue">
          <span>开关:</span>
          <span v-if="ruleForm.content[2].switch">打开</span>
          <span v-if="!ruleForm.content[2].switch">关闭</span>
        </div>
        <div class="textNameTX1 padding-l60" v-if="ruleForm.content[3].istrue">
          <span>音量:</span>
          <span>{{ruleForm.content[3].volume}}</span>
        </div>
        <div class="textNameTX1 padding-l60" v-if="ruleForm.content[4].istrue">
          <span>语音播报:</span>
          <span>{{ruleForm.content[4].notice}}</span>
        </div>
        <div class="textNameTX1">备注：{{ruleForm.remarks}}</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="secondaryConfirmation(2)">返 回</el-button>
        <el-button type="primary" @click="secondaryConfirmation(1)">确 定</el-button>
      </span>
    </el-dialog>
    <configure-log v-if="isconfigureLog" :logData="logData" @beforeCloseEven="beforeCloseEven"></configure-log>
    <my-equipment v-if="isEquipmentShow" @equipmentEvemt="equipmentEvemt" :idsList="idsss"></my-equipment>
  </section>
</template>
<script>
import { customerlist, configlist, configadd, commonexcelupload } from 'api/txEquipment/index'
import common from 'src/util/common.js'
import ctable from 'components/common/ctable'
import paginate from 'components/common/paginate'
import configureLog from 'components/configureLog.vue'
import myEquipment from 'components/myEquipment'
import { vueTimeFormat } from 'src/filter/index'
export default {
  data () {
    return {
      dateTstart: {
        disabledDate: time => {
          return (
            time.getTime() > (this.form.Timepicker[1] || Date.now())
          )
        }
      },
      dateTend: {
        disabledDate: time => {
          return (
            time.getTime() > Date.now() || time.getTime() < (this.form.Timepicker[0] || (Date.now() - 8.64e7))
          )
        }
      },
      isDialogVisible: false,
      isEquipmentShow: false,
      isconfigureLog: false,
      isDialogShow: false,
      formLabelWidth: '120px',
      formLabelWidth2: '60px',
      ruleForm: {
        type: 1,
        device_list: [],
        file: [],
        content: [
          {istrue: false, type: null},
          {istrue: false, temperature: null},
          {istrue: false, switch: false},
          {istrue: false, volume: null},
          {istrue: false, notice: null}
        ],
        remarks: ''
      },
      rules: {
        device_list: [
          { required: true, message: '请选择设备列表', trigger: 'change' }
        ],
        file: [
          { required: true, message: '请上传文件', trigger: 'change' }
        ],
        remarks: [
          { required: true, message: '请输入备注信息', trigger: 'blur' }
        ]
      },
      idsss: [],
      logData: {},
      listscustomer: [],
      form: {
        user_id: '',
        Timepicker: [] // 缴费日期
      },
      formObj: {},
      pageObj: { // 分页
        page: {},
        callback: this.getData
      }
    }
  },
  created () {
    this.filterObjEvemt()
    customerlist({
      pageIndex: 0,
      pageSize: 1000
    }).then(res => {
      this.listscustomer = res.data
    })
  },
  components: {
    ctable,
    myEquipment,
    paginate,
    configureLog
  },
  methods: {
    queryEquipmentFun () {
      this.idsss = []
      this.isEquipmentShow = true
    },
    delfile (index) {
      this.ruleForm.file.splice(index, 1)
      this.$refs.ruleForm.validateField('file')
    },
    handlePreview (file) {
      let type = ['xls', 'xlsx']
      let flag = type.some(val => {
        return file.name.endsWith(`.${val}`)
      })
      if (!flag) {
        this.$alert(`请上传以.${type.join(',或.')}结尾的文件`, '上传失败', {
          confirmButtonText: '确定'
        })
      } else {
        console.log(!flag, type)
        // this.ruleForm.fileObj = file
        var formFile = new FormData()
        formFile.append('file', file.raw)
        commonexcelupload(formFile).then(res => {
          console.log(this.ruleForm)
          this.ruleForm.file.push.apply(this.ruleForm.file, res.data.device_list)
          // this.$message({
          //   message: '上传成功',
          //   type: 'success'
          // })
          this.$refs.ruleForm.validateField('file')
        })
      }
    },
    equipmentEvemt (obj) {
      if (obj.type === 1) {
        this.ruleForm.device_list = obj.lists
        this.idsss = obj.lists
      }
      this.$refs.ruleForm.validateField('device_list')
      this.isEquipmentShow = false
    },
    vueTimeFormats (value) {
      return vueTimeFormat(value, 'yyyy-MM-dd')
    },
    submitForm (formName, num) {
      if (num === 1) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.isDialogVisible = true
          }
        })
      } else {
        this.$refs[formName].resetFields()
        this.isDialogShow = false
      }
    },
    secondaryConfirmation (num) {
      if (num === 1) {
        this.$confirm('确定执行本次批量设置吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let pan = {content: {}}
          this.ruleForm.content.forEach((oo, index) => {
            if (oo.istrue && index === 0 && oo.model !== '') pan.content.type = oo.type
            if (oo.istrue && index === 1 && oo.model !== '') pan.content.temperature = oo.temperature
            if (oo.istrue && index === 2) pan.content.switch = oo.switch
            if (oo.istrue && index === 3 && oo.model !== '') pan.content.volume = Number(oo.volume)
            if (oo.istrue && index === 4 && oo.model !== '') pan.content.notice = oo.notice
          })
          pan.device_list = this.ruleForm.device_list
          if (this.ruleForm.type === 2) {
            pan.device_list = this.ruleForm.file
            pan.file = undefined
          }
          pan.remarks = this.ruleForm.remarks
          configadd(pan).then(res => {
            this.$message({
              message: '添加成功',
              type: 'success'
            })
            this.isDialogVisible = false
            this.isDialogShow = false
            this.getData(1)
          })
        })
      } else {
        this.isDialogVisible = false
      }
    },
    getData (int) { // 获取数据
      configlist({
        pageIndex: int - 1,
        pageSize: 10,
        ...this.formObj
      }).then(res => {
        this.lists = res.data
        this.pageObj.page = res.page
      })
    },
    search () {
      this.filterObjEvemt()
    },
    // 新增厂商
    addFirm () {
      this.ruleForm = {
        type: 1,
        device_list: [],
        file: [],
        content: [
          {istrue: false, type: null},
          {istrue: false, temperature: null},
          {istrue: false, switch: false},
          {istrue: false, volume: null},
          {istrue: false, notice: null}
        ],
        remarks: ''
      }
      this.isDialogShow = true
    },
    // 编辑厂商
    editFirm (data) {
      this.logData = data
      this.isconfigureLog = true
    },
    beforeCloseEven () {
      this.isconfigureLog = false
    },
    filterObjEvemt () {
      let obj = {}
      for (const key in this.form) {
        if (this.form[key] === '' || this.form[key] === null || this.form[key] === undefined) continue
        switch (key) {
          case 'Timepicker':
            if (this.form.Timepicker.length && this.form.Timepicker[0] && this.form.Timepicker[1]) {
              obj.start_time = this.vueTimeFormats(parseInt(common.div((new Date(this.form.Timepicker[0])).getTime(), 1000)))
              obj.end_time = this.vueTimeFormats(parseInt(common.div((new Date(this.form.Timepicker[1])).getTime(), 1000)))
            }
            break
          default:
            obj[key] = this.form[key]
            break
        }
      }
      this.formObj = JSON.parse(JSON.stringify(obj))
      this.getData(1)
      return obj
    }
  }
}
</script>
<style lang="less">
  .itemBoxName .el-form-item__error{
    z-index: 100;
    top: 60%;
  }
  .firm-manage {
    .customWidth{
      min-width: 560px;
    }
  }
</style>
<style lang="less" scoped>
.firm-manage {
  .customWidth{
    min-width: 560px;
  }
  .width200{width: 200px;}
  .title {
    overflow: hidden;
    padding: 16px 30px;
    padding-bottom: 0;
  }
  .search-box {
    padding: 20px 30px;
    background: #ffffff;
  }
  .data-list {
    padding: 10px 30px;
  }
  .choose {
    margin-right: 10px;
    .select-box {
      width: 120px;
    }
    .year-box {
      width: 150px;
    }
  }
  .titleright{
    float: right;
    margin-left: 20px;
  }
  .textNameTX1{
    padding-bottom: 10px;
    color: #333;
    font-size: 14px;
  }
  .padding-l60{padding-left: 60px;}
}
</style>
